package ucuserslogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryInviteDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryInviteDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryInviteDataLogic {
	return &QueryInviteDataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 获取用户支付账户列表
func (l *QueryInviteDataLogic) QueryInviteData(in *pb.QueryInviteReq) (*pb.QueryInviteResp, error) {
	defer utils.RecoverPanic()

	uid := in.Uid
	// 处理时间
	l.Logger.Infof("QueryInviteData start. in: %+v", in)
	now := time.Now()
	loc, _ := time.LoadLocation(dbkey.DateTimeZone)
	st := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc).AddDate(0, 0, 0)
	et := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, loc).AddDate(0, 0, 0)
	//查询总收入
	resp := &pb.QueryInviteResp{}
	var err error
	inviteTotalIncome, err := l.svcCtx.UserInviteOrderFlowModel.SumOrderAmount(l.ctx, uid, 0, nil, nil)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	//当天总收入
	inviteTodayIncome, err := l.svcCtx.UserInviteOrderFlowModel.SumOrderAmount(l.ctx, uid, 0, &st, &et)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	//总邀请人数
	inviteTotalPerNum, err := l.svcCtx.UserInviteModel.SumInviteTotalPerCount(l.ctx, uid, nil, nil)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	//当天邀请人数
	inviteTodayPerNum, err := l.svcCtx.UserInviteModel.SumInviteTotalPerCount(l.ctx, uid, &st, &et)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	//当前余额
	userWallet, err := l.svcCtx.UserWalletModel.FindOneByUidMoneyType(l.ctx, uid, walletkey.UsingCurrencyType)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	l.Logger.Infof("QueryInviteData start. resp: %+v, inviteTotalIncome: %d , inviteTodayIncome: %d , inviteTotalPerNum: %d, inviteTodayPerNum: %d", resp, inviteTotalIncome, inviteTodayIncome, inviteTotalPerNum, inviteTodayPerNum)
	resp.InviteTotalIncome = inviteTotalIncome
	resp.InviteTodayIncome = inviteTodayIncome
	resp.InviteTotalPerNum = inviteTotalPerNum
	resp.InviteTodayPerNum = inviteTodayPerNum
	l.Logger.Infof("QueryInviteData start. InviteTotalIncome: %+v", resp.InviteTotalIncome)
	// 判断用户是否存在钱包
	if userWallet != nil {
		resp.Balance = userWallet.Amount
	}
	return resp, nil
}
